//对象转URL参数
function queryParams(data = {}, isPrefix = true, arrayFormat = "comma") {
  let prefix = isPrefix ? "?" : "";
  let _result = [];
  if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
    arrayFormat = "comma";
  for (let key in data) {
    let value = data[key];
    // 去掉为空的参数
    if (["", undefined, null].indexOf(value) >= 0) {
      continue;
    }
    // 如果值为数组，另行处理
    if (value.constructor === Array) {
      // e.g. {ids: [1, 2, 3]}
      switch (arrayFormat) {
        case "indices":
          // 结果: ids[0]=1&ids[1]=2&ids[2]=3
          for (let i = 0; i < value.length; i++) {
            _result.push(key + "[" + i + "]=" + value[i]);
          }
          break;
        case "brackets":
          // 结果: ids[]=1&ids[]=2&ids[]=3
          value.forEach(_value => {
            _result.push(key + "[]=" + _value);
          });
          break;
        case "repeat":
          // 结果: ids=1&ids=2&ids=3
          value.forEach(_value => {
            _result.push(key + "=" + _value);
          });
          break;
        case "comma":
          // 结果: ids=1,2,3
          let commaStr = "";
          value.forEach(_value => {
            commaStr += (commaStr ? "," : "") + _value;
          });
          _result.push(key + "=" + commaStr);
          break;
        default:
          value.forEach(_value => {
            _result.push(key + "[]=" + _value);
          });
      }
    } else {
      _result.push(key + "=" + value);
    }
  }
  return _result.length ? prefix + _result.join("&") : "";
}

//URL参数转对象
function queryObj(params = "", arrayFormat = "comma") {
  let nullArr = [undefined, null];
  let pre_idx = params.indexOf("?");
  let result = {},
    _params = params;
  if (pre_idx != -1) {
    _params = _params.slice(pre_idx + 1);
  }
  let arr = _params.split("&");
  if (["indices", "brackets", "repeat", "comma"].indexOf(arrayFormat) == -1)
    arrayFormat = "comma";
  arr.reduce((acc, curr, idx, arr) => {
    let i = curr.indexOf("=");
    let k = curr.slice(0, i),
      v = curr.slice(i + 1);
    switch (arrayFormat) {
      case "indices":
        break;
      case "brackets":
        break;
      case "repeat":
        if (nullArr.includes(acc[k])) {
          acc[k] = v;
        } else {
          if (!Array.isArray(acc[k])) {
            acc[k] = [acc[k]];
          }
          acc[k].push(v);
        }
        break;
      case "comma":
        if (nullArr.includes(acc[k])) {
          let comma_idx = v.indexOf(",");
          if (comma_idx != -1) {
            acc[k] = v.split(",");
          } else {
            acc[k] = v;
          }
        }
        break;
      default:
        break;
    }
    return acc;
  }, result);
  return result;
}

export { queryParams, queryObj };
